package com.sheep.juc;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangze
 * @date 2020-10-19 11:20.
 **/
public class BlockedQueue<T> {
	private final Lock lock=new ReentrantLock();
	private final Condition notEmpty=lock.newCondition();
	private final Condition notFull=lock.newCondition();

	private int size;

	private Queue<T>  queue=new LinkedList<T>();

	public BlockedQueue(int size){
		this.size=size;
	}

	// 入队
	public boolean  enq(T t){
		lock.lock();
		try {
			if(queue.size()==size){
				return false;
			}
			while (queue.size()==size){
				notFull.await();
			}
			queue.offer(t);
			notEmpty.signalAll();
			return  true;
		}
		catch (InterruptedException e){
			throw  new RuntimeException(e);
		}
		finally {
			lock.unlock();
		}
	}

	// 出队
	public T  deq(){
		lock.lock();
		if(queue.size()==0){
			throw  new RuntimeException("队列为空");
		}
		try {

			while (queue.size()==0){
				notEmpty.await();
			}
			T r= queue.poll();
			notFull.signalAll();
			return  r;
		}
		catch (InterruptedException e){
			throw  new RuntimeException(e);
		}
		finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		BlockedQueue<Integer> blockedQueue=new BlockedQueue(2);
		blockedQueue.enq(1);
		blockedQueue.enq(2);
		blockedQueue.deq();

		System.out.println(blockedQueue.size);
	}
}
